/*************************************************************************
	Create Fonts with Images
	
*************************************************************************/

using UnityEditor;
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.IO;

public class UTVPFontGenerator : EditorWindow
{
	
	private GUISkin inspectorSkin = EditorGUIUtility.GetBuiltinSkin(EditorSkin.Inspector);
	
	private class GlyphInfo
	{
		public Texture2D tex;
		public string str;
		
		public GlyphInfo(Texture2D tex, string str)
		{
			this.tex = tex;
			this.str = str;
		}
	}
	
	private List<GlyphInfo> m_CurrSelectedObjs = new List<GlyphInfo>();
	private int m_MaximumAtlasSize = 2048;
	private int m_BaseHeight = 0;
	private int m_Padding = 2;
	private Vector2 m_TextureListScrollPos = Vector2.zero;
	private string m_SpriteInfoFilePath = "";

	
	[MenuItem ("UKag/UTVP Font Generator")]
	static void Init ()
	{
        // Get existing open window or if none, make a new one:
        EditorWindow editor = EditorWindow.GetWindow (typeof (UTVPFontGenerator));
		editor.minSize = new Vector2(300, 200);
		editor.title = "Font Generator";
    }
	
	int ComparisonTexture(GlyphInfo x, GlyphInfo y)
	{
		return x.tex.name.CompareTo(y.tex.name);
	}
	
	void OnSelectionChange ()
	{
		if (Selection.objects.Length == 1)
		{
			if (Selection.objects[0] is UTVPBMFontInfoAsset)
			{
				m_SpriteInfoFilePath = AssetDatabase.GetAssetPath(Selection.objects[0]).Substring("Assets/".Length);
				m_SpriteInfoFilePath = m_SpriteInfoFilePath.Substring(0, m_SpriteInfoFilePath.LastIndexOf(".asset"));
				Repaint();
			}
			return;
		}
		m_CurrSelectedObjs.Clear();
		for (int i=0; i<Selection.objects.Length; i++)
		{
			Object obj = Selection.objects[i];
			if (obj is Texture2D)
				m_CurrSelectedObjs.Add(new GlyphInfo((Texture2D)obj, obj.name.Substring(obj.name.Length - 1)));
		}
		
		Repaint();
	}
	
	void OnGUI ()
	{
		EditorGUIUtility.LookLikeControls();
		
		GUILayout.BeginHorizontal();
		GUILayout.Label("Glyph Image List:", GUILayout.Width(Screen.width - 100));
		if (GUILayout.Button("Sort"))
			m_CurrSelectedObjs.Sort(ComparisonTexture);
		GUILayout.EndHorizontal();
		
		m_TextureListScrollPos = GUILayout.BeginScrollView(m_TextureListScrollPos, inspectorSkin.box, GUILayout.Height((Screen.height - 140)));
		for(int i=0; i<m_CurrSelectedObjs.Count; i++) {
			GUILayout.BeginHorizontal();
			GUILayout.Label(m_CurrSelectedObjs[i].tex.name);
			m_CurrSelectedObjs[i].str = GUILayout.TextField(m_CurrSelectedObjs[i].str, GUILayout.Width(100));
			if(m_CurrSelectedObjs[i].str.Length == 0)
				m_CurrSelectedObjs[i].str = "x";
			if(GUILayout.Button("Remove", GUILayout.Width(100))) {
				m_CurrSelectedObjs.RemoveAt(i);
				return;
			}
			GUILayout.EndHorizontal();
		}
		GUILayout.EndScrollView();
		m_BaseHeight = EditorGUILayout.IntField("BaseHeight", m_BaseHeight);
		m_Padding = EditorGUILayout.IntField("Padding", m_Padding);
		m_MaximumAtlasSize = EditorGUILayout.IntField("MaxAtlasSize", m_MaximumAtlasSize);

		EditorGUILayout.Space();
		
		GUILayout.BeginHorizontal();
		m_SpriteInfoFilePath = EditorGUILayout.TextField("FontInfoFilePath", m_SpriteInfoFilePath);

		if (GUILayout.Button("Create", GUILayout.Width(100))) {
			if (m_CurrSelectedObjs.Count == 0)
				return;
			
			Texture2D atlasTex = new Texture2D(256, 256, TextureFormat.ARGB32, false);
			Texture2D[] textures = new Texture2D[m_CurrSelectedObjs.Count];
			for (int i=0; i<m_CurrSelectedObjs.Count; i++) {
				textures[i] = m_CurrSelectedObjs[i].tex;
				string texPath = AssetDatabase.GetAssetPath(textures[i]);
				TextureImporter texImporter = (TextureImporter)AssetImporter.GetAtPath(texPath);
				if (!texImporter.isReadable || texImporter.textureFormat != TextureImporterFormat.ARGB32) {
					texImporter.isReadable = true;
					texImporter.textureFormat = TextureImporterFormat.ARGB32;
					AssetDatabase.WriteImportSettingsIfDirty(texPath);
				}
			}
			AssetDatabase.Refresh();
			Rect[] rects = atlasTex.PackTextures(textures, m_Padding, m_MaximumAtlasSize);
			int atlasWidth = atlasTex.width;
			int atlasHeight = atlasTex.height;
			if (textures[0].width - 1 > atlasWidth * rects[0].width || textures[0].height - 1 > atlasHeight * rects[0].height) {
				Debug.LogError("UTVPSpriteEditor: Atlas Size Overflow!");
				return;
			}
			UTVPBMFontInfoAsset fontAsset = ScriptableObject.CreateInstance<UTVPBMFontInfoAsset>();
			fontAsset.FontInfo = new UTVPBMFontInfo();
			if (m_SpriteInfoFilePath.IndexOf('/') > 0)
				fontAsset.FontInfo.ImageName = m_SpriteInfoFilePath.Substring(m_SpriteInfoFilePath.LastIndexOf('/') + 1);
			else
				fontAsset.FontInfo.ImageName = m_SpriteInfoFilePath;
			fontAsset.FontInfo.Face = fontAsset.FontInfo.ImageName;
			fontAsset.FontInfo.Size = textures[0].height;
			fontAsset.FontInfo.LineHeight = textures[0].height;
			fontAsset.FontInfo.BaseHeight = m_BaseHeight;
			fontAsset.FontInfo.Glyphs = new UTVPGlyphInfo[rects.Length];
			UTVPGlyphInfo glyph = null;
			for (int i=0; i<m_CurrSelectedObjs.Count; i++) {
				glyph = new UTVPGlyphInfo();
				glyph.Ch = (int)(m_CurrSelectedObjs[i].str[m_CurrSelectedObjs[i].str.Length - 1]);
				glyph.Width = (int)(atlasWidth * rects[i].width + 0.5f);
				glyph.Height = (int)(atlasHeight * rects[i].height + 0.5f);
				glyph.X = (int)(atlasWidth * rects[i].x + 0.5f);
				glyph.Y = atlasHeight - (int)(atlasHeight * rects[i].y + 0.5f) - glyph.Height;
				glyph.XAdvance = glyph.Width;
				fontAsset.FontInfo.Glyphs[i] = glyph;
			}

			byte[] pngData = atlasTex.EncodeToPNG();
			string imgPath = "Assets/" + m_SpriteInfoFilePath;
			File.WriteAllBytes(imgPath + ".png", pngData);
			AssetDatabase.Refresh();
			Texture2D atlas = AssetDatabase.LoadAssetAtPath(imgPath + ".png", typeof(Texture2D)) as Texture2D;
			fontAsset.Texture = atlas;
			
			AssetDatabase.CreateAsset(fontAsset, imgPath + ".asset");
			AssetDatabase.Refresh();
		}
		GUILayout.EndHorizontal();
	}

}
